<?php

declare(strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;
use app\common\controller\Config;

class DealOrder extends Base
{
    protected $name = 'deal_order';

    protected $type = [
        'pay_time' => 'timestamp',
        'refund_time' => 'timestamp',
        'finish_time' => 'timestamp',
    ];
    public function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')->field('id,code,nickname,mobile');
    }
    public function buser()
    {
        return $this->hasOne(User::class, 'id', 'buy_uid')->field('id,code,nickname,mobile');
    }
    public function getStatusTextAttr($value, $data)
    {
        return self::getStatusList($data['status'], 1);
    }
    /**
     * 状态
     */
    public static function getStatusList($value, $type = 1)
    {
        $status = [1 => '待支付', 2 => '待收款', 3 => '已完成', 4 => '已撤销'];
        return $type == 1 ? $status[$value] : $status;
    }
    public function getTypeTextAttr($value, $data)
    {
        return self::getDealType($data['type']);
    }

    public static function getDealType($value, $type = 1)
    {
        $status = [1 => '买单', 2 => '卖单'];
        return $type == 1 ? $status[$value] : $status;
    }
    /**
     * 修改订单
     */
    public static function edit($param, $user): array
    {
        parent::startTrans();
        try {
            $info = parent::where(['id' => $param['id']])->find();
            if (empty($info)) {
                return ['code' => -1, 'msg' => '交易单不存在'];
            }
            switch ($param['type']) {
                case 'clear': //撤销订单
                    if ($info->status >2) {
                        return ['code' => -1, 'msg' => '已支付，无法撤销'];
                    }
                    if ($info->is_refund != 1) {
                        return ['code' => -1, 'msg' => '该交易已撤销！不可重复提交'];
                    }
                    $info->refund_time = time();
                    $info->is_refund = 2;
                    $info->status = 4;
                    $info->save();
                    Target::Account()->basics($info->buy_uid, 'currency', $info->buy_ratio, '撤销买家手续费返还', '+')->createNormal();
                    if ($info->getData('type') == 2) {
                        Target::Account()->basics($info->uid, 'currency', $info->buy_ratio, '撤销卖家手续费返还', '+')->createNormal();
                        Target::Account()->basics($info->uid, 'sold', floatval($info->num), '撤销交易卖家返还可出售', '+')->createNormal();
                        Target::Account()->basics($info->uid, 'freeze', floatval($info->num), '撤销交易卖家扣除冻结', '-')->createNormal();
                    }else{
                        $deal = Deal::where(['id' => $info->deal_id])->find();
                        if ($deal->getData('type') == 2) {
                            Target::Account()->basics($info->uid, 'currency', $info->buy_ratio, '撤销卖家手续费返还', '+')->createNormal();
                            Target::Account()->basics($info->uid, 'sold', floatval($info->num), '撤销交易卖家返还可出售', '+')->createNormal();
                            Target::Account()->basics($info->uid, 'freeze', floatval($info->num), '撤销交易卖家扣除冻结', '-')->createNormal();
                        }
                    }
                    $money = parent::where(['deal_id' => $info->deal_id])->sum('num');
                    $num = Deal::where(['id' => $info->deal_id])->find();
                    if ($money >= $num['num']) {
                        $num->repeal_time = time();
                        $num->status = 3;
                        $num->save();
                    }
                    parent::commit();
                    return ['code' => 1, 'msg' => '交易撤销成功！', 'url' => url('deal/my_deal_list')->build() . '?type=1&status=4'];
                case "receipt": //确认收款
                    if ($info->status != 2) {
                        return ['code' => -1, 'msg' => '状态错误'];
                    }
                    $info->status = 3;
                    $info->finish_time = time();
                    $info->save();
                    $num_money = floatval($info->num);
                    Target::Account()->basics($info->buy_uid, 'wait', $num_money, '交易完成买家收益', '+')
                        ->createNormal();
                    $shopuser = User::where(['id' => $info->uid])->find();
                    if ($shopuser->assets->freeze > $num_money) {
                        $shopmoney = $num_money;
                    } else {
                        $shopmoney = $shopuser->assets->freeze;
                    }
                    Target::Account()->basics($info['uid'], 'freeze', $shopmoney, '交易完成卖家冻结扣除', '-')
                        ->createNormal();

                    $deal = Deal::where(['id' => $info->deal_id])->find();
                    $count = parent::where(['deal_id' => $info->deal_id, 'status' => 3])->sum('num');
                    if ($count == $deal->num) {
                        $deal->status = 2;
                        $deal->save();
                    }
                    /**
                     * 奖励
                     */
                    $muser = User::where(['id' => $info->buy_uid])->find();
                    $res = Relation::lock_reward($info, $muser);

                    // print_r($res);die;
                    parent::commit();
                    return ['code' => 1, 'msg' => '确认收款成功！', 'url' => url('deal/my_deal_list')->build() . '?type=2&status=3'];
                default:
                    return ['code' => -1, 'msg' => '加载失败'];
            }
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 交易单未付款撤销
     */
    public static function repealOrder()
    {
        $sys = Config::lists();
        $time = time() - 3600 * 3;
        try {
            $list = parent::where(['pay_time' => 0, 'status' => 1, 'is_refund' => 1])->where('create_time', '<', $time)->select();
            if (!$list->isEmpty()) {
                foreach ($list as &$info) {
                    $info->refund_time = time();
                    $info->is_refund = 2;
                    $info->status = 4;
                    $info->save();
                    Target::Account()->basics($info->buy_uid, 'currency', $info->buy_ratio, '买家未支付系统撤销手续返还', '+')->createNormal();
                    if ($info->getData('type') == 2) {
                        Target::Account()->basics($info->uid, 'currency', $info->buy_ratio, '撤销卖家手续费返还', '+')->createNormal();
                        Target::Account()->basics($info->uid, 'sold', floatval($info->num), '撤销交易卖家返还可出售', '+')->createNormal();
                        Target::Account()->basics($info->uid, 'freeze', floatval($info->num), '撤销交易卖家扣除冻结', '-')->createNormal();
                    } else {
                        $deal = Deal::where(['id' => $info->deal_id])->find();
                        if ($deal->getData('type') == 2) {
                            Target::Account()->basics($info->uid, 'currency', $info->buy_ratio, '撤销卖家手续费返还', '+')->createNormal();
                            Target::Account()->basics($info->uid, 'sold', floatval($info->num), '撤销交易卖家返还可出售', '+')->createNormal();
                            Target::Account()->basics($info->uid, 'freeze', floatval($info->num), '撤销交易卖家扣除冻结', '-')->createNormal();
                        }
                    }
                    $money = parent::where(['deal_id' => $info->deal_id])->sum('num');
                    $num = Deal::where(['id' => $info->deal_id, 'status' => 1])->find();
                    if ($money >= $num['num']) {
                        $num->repeal_time = time();
                        $num->status = 3;
                        $num->save();
                    }
                }
                return ['code' => 1, 'msg' => '撤销成功！'];
            } else {
                return ['code' => -1, 'msg' => '暂无交易单！'];
            }
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 凌晨撤单
     */
    public static function autoRevokelOrder()
    {
        return self::revokelOrder(1);
    }
    /**
     * 周撤单
     */
    public static function weekRevokelOrder()
    {
        $system = Config::lists();
        $week = explode(',', $system['deal_week']);
        if (!in_array(date('w'), $week)) {
            return self::revokelOrder(2);
        }
        return ['code' => -1, 'msg' => '暂无撤单！'];
    }
    /**
     * 自动撤单
     */
    public static function revokelOrder($type = 1)
    {
        try {
            $map[] = ['status', '=', 1];
            if ($type == 1) {
                $map[] = ['type', '=', 1];
                $list = Deal::where($map)->whereDay('create_time', 'yesterday')->select();
            } else {
                $list = Deal::where($map)->select();
            }
            if (!$list->isEmpty()) {
                foreach ($list as &$info) {
                    $money = parent::where(['deal_id' => $info->id])->sum('num');
                    $buy_ratio = parent::where(['deal_id' => $info->id])->sum('buy_ratio');

                    if ($info->getData('type') == 2) {
                        Target::Account()->basics($info->uid, 'sold', round($info->num - $money, 2), '系统自动撤销可出售返还', '+')->createNormal();
                        Target::Account()->basics($info->uid, 'freeze', round($info->num - $money, 2), '系统自动撤销冻结账户返还', '-')->createNormal();
                    }
                    Target::Account()->basics($info->uid, 'currency', round($info->buy_ratio - $buy_ratio, 2), '系统自动撤销交易手续返还', '+')->createNormal();
                    $orderList = parent::where(['pay_time' => 0, 'deal_id' => $info->id, 'status' => 1, 'is_refund' => 1])->select();
                    if (!$orderList->isEmpty()) {
                        foreach ($orderList as &$v) {
                            $v->refund_time = time();
                            $v->is_refund = 2;
                            $v->status = 4;
                            $v->save();
                            Target::Account()->basics($v->buy_uid, 'currency', $v->buy_ratio, '系统自动撤销买家手续返还', '+')->createNormal();
                        }
                    }
                    $info->repeal_time = time();
                    $info->status = 3;
                    $info->save();
                }
                return ['code' => 1, 'msg' => '撤销成功！'];
            } else {
                return ['code' => -1, 'msg' => '无撤单！'];
            }
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 交易单未付款撤销
     */
    public static function myrepealOrder($id)
    {
        $sys = Config::lists();
        $time = time() - 3600 * 3;
        try {
            $list = parent::where(['pay_time' => 0, 'status' => 1, 'is_refund' => 1, 'id' => $id])->where('create_time', '<', $time)->select();
            if (!$list->isEmpty()) {
                foreach ($list as &$info) {
                    $info->refund_time = time();
                    $info->is_refund = 2;
                    $info->status = 4;
                    $info->save();
                    // Target::Account()->basics($info->buy_uid, 'currency', $info->buy_ratio, '买家未支付系统撤销手续返还', '+')->createNormal();
                    if ($info->getData('type') == 2) {
                        Target::Account()->basics($info->uid, 'currency', $info->buy_ratio, '撤销卖家手续费返还', '+')->createNormal();
                        Target::Account()->basics($info->uid, 'sold', floatval($info->num), '撤销交易卖家返还可出售', '+')->createNormal();
                        Target::Account()->basics($info->uid, 'freeze', floatval($info->num), '撤销交易卖家扣除冻结', '-')->createNormal();
                    } else {
                        $deal = Deal::where(['id' => $info->deal_id])->find();
                        if ($deal->getData('type') == 2) {
                            Target::Account()->basics($info->uid, 'currency', $info->buy_ratio, '撤销卖家手续费返还', '+')->createNormal();
                            Target::Account()->basics($info->uid, 'sold', floatval($info->num), '撤销交易卖家返还可出售', '+')->createNormal();
                            Target::Account()->basics($info->uid, 'freeze', floatval($info->num), '撤销交易卖家扣除冻结', '-')->createNormal();
                        }
                    }
                }
                return ['code' => 1, 'msg' => '撤销成功！'];
            } else {
                return ['code' => -1, 'msg' => '暂无交易单！'];
            }
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
